﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using OestsCommon.Model;

namespace OestsDataBase
{
	public static class StudentDAL
	{
		//学生
		public static void CreateTable()
		{
			string sqlCheck = "if object_id( 'T_Student') is not null select 1 else select 0";
			if ((int)SqlHelper.ExecuteScalar(sqlCheck) == 0)
			{
				string sqlCreacte = @"CREATE TABLE T_Student (id bigint identity(1,1) ,
															number NVARCHAR(20) primary key,
															name NVARCHAR(20) not null,
															class NVARCHAR(20) not null,
															password NVARCHAR(20),
															teacher_id bigint ,
															major_id bigint not null,
															login_time datetime,
															logout_time datetime，
															theory_error NVARCHAR(max),
															operate_error NVARCHAR(max))";

				SqlHelper.ExecuteNonQuery(sqlCreacte);
			}
			//else
			//{
			//    string sql = "dbcc  checkident(T_Student,RESEED,0)";
			//    SqlHelper.ExecuteNonQuery(sql);
			//}
		}
		public static List<Student> GetData()
		{
			List<Student> list = new List<Student>();
			string strSql = "select * from T_Student ";
			DataTable dt = SqlHelper.ExecuteDataTable(strSql);
			if (dt == null) { return null; }
			foreach (DataRow dr in dt.Rows)
			{
				list.Add(ReadData(dr));
			}
			return list;

		}

		public static List<Student> GetStudentByClass(string className)
		{
			List<Student> list = new List<Student>();
			string strSql = "select * from T_Student where class =@classname";
			DataTable dt = SqlHelper.ExecuteDataTable(strSql, new SqlParameter("@classname", className));
			if (dt == null) { return null; }
			foreach (DataRow dr in dt.Rows)
			{
				list.Add(ReadData(dr));
			}
			return list;
		}
		public static Student GetStudentByNumber(string number)
		{
			string strSql = "select * from T_Student where number=@number";
			DataTable dt = SqlHelper.ExecuteDataTable(strSql, new SqlParameter("@number", number));
			if (dt == null || dt.Rows.Count == 0)
			{
				return null;
			}
			DataRow dr = dt.Rows[0];
			return ReadData(dr);
		}

		private static Student ReadData(DataRow dr)
		{
			Student s = new Student();
			s.DBid = Int32.Parse(dr["id"].ToString());
			s.Number = dr["number"].ToString();
			s.Name = dr["name"].ToString();
			s.ClassName = dr["class"].ToString();
			s.Password = dr["password"].ToString();
			s.TeacherId = dr["teacher_id"].Equals(DBNull.Value) ? -1 : Int32.Parse(dr["teacher_id"].ToString());
			s.MajorId = Int32.Parse(dr["major_id"].ToString());
			if (!dr["theory_error"].Equals(DBNull.Value))
			{
				string strTheoryError = dr["theory_error"].ToString();
				s.TheoryErrorList = LitJson.JsonMapper.ToObject<List<TheoryError>>(strTheoryError);

				
			}
			if (!dr["operate_error"].Equals(DBNull.Value))
			{
				string str = dr["operate_error"].ToString();
				s.OperateErrorList = LitJson.JsonMapper.ToObject<List<OperateError>>(str);
			}

			//if (!DBNull.Value.Equals(dr["pattern"]))
			//{
			//	string strType = dr["pattern"].ToString();
			//	s.CurrenPattern = (PatternType)Enum.Parse(typeof(PatternType), strType, false);
			//}
			return s;
		}

		public static void SaveLoginTime(int id)
		{
			DateTime date = DateTime.Now;
			string strSql = string.Format("update T_Student set login_time='{0}' where id = @id", date);
			int n = SqlHelper.ExecuteNonQuery(strSql, new SqlParameter("@id", id));
		}

		public static void SaveLogoutTime(int id)
		{
			DateTime date = DateTime.Now;
			string strSql = string.Format("update T_Student set logout_time='{0}' where id = @id", date);
			int n = SqlHelper.ExecuteNonQuery(strSql, new SqlParameter("@id", id));
		}

		/// <summary>
		/// TODO:学生表还需要添加属性
		/// </summary>
		/// <param name="s"></param>
		/// <returns></returns>
		public static int AddStudent(Student s)
		{
			string strSql = string.Format("insert into T_Student (number, password, class, name, major_id) values('{0}','{1}','{2}','{3}',{4});SELECT @@Identity",
				s.Number, s.Password, s.ClassName, s.Name, s.MajorId);
			object obj = SqlHelper.ExecuteScalar(strSql);
			return Int32.Parse(obj.ToString());
		}

		/// <summary>
		/// 删除一条教师信息
		/// </summary>
		/// <param name="id"></param>
		/// <returns></returns>
		public static bool DeleteStudent(int id)
		{
			string strSql = string.Format("delete from T_Student where id = @id");
			int n = SqlHelper.ExecuteNonQuery(strSql, new SqlParameter("@id", id));
			if (n != 0)
			{
				return true;
			}
			return false;

		}
		public static bool ModifyStudent(Student s)
		{
			string strSql = string.Format("update T_Student set number='{0}',password='{1}',class='{2}',name='{3}',major_id='{4}' where id = @id",
				s.Number, s.Password, s.ClassName, s.Name, s.MajorId);
			int n = SqlHelper.ExecuteNonQuery(strSql, new SqlParameter("@id", s.DBid));
			if (n != 0)
			{
				return true;
			}
			return false;
		}


		/// <summary>
		/// 学生属于哪个教师的管理
		/// </summary>
		/// <param name="stuId"></param>
		/// <param name="teacherId"> -1 表示移除</param>
		/// <returns></returns>
		public static bool SetStudentManage(int stuId, int teacherId = -1)
		{
			string strSql = string.Format("update T_Student set teacher_id={0}  where id = @id", teacherId);
			int n = SqlHelper.ExecuteNonQuery(strSql, new SqlParameter("@id", stuId));
			if (n != 0)
			{
				//清空当前学生的模式设置(保证学生的模式设置是针对该老师的设置)
				ClearPattern(stuId);
				return true;
			}
			return false;
		}

		public static void ClearPattern(int studentId)
		{
			string strSql = string.Format("update T_Student set pattern={0}  where id = @id", "NULL");
			SqlHelper.ExecuteNonQuery(strSql, new SqlParameter("@id", studentId));
		}

		//public static bool ModifyUserPwd(string pwd)
		//{
		//    string strSql = string.Format("update T_Student set password='{0}'  where id = @id", pwd);
		//    int n = SqlHelper.ExecuteNonQuery(strSql, new SqlParameter("@id", Global._UserData.DBid));
		//    if (n != 0)
		//    {
		//        Global._UserData.Password = pwd;
		//        return true;
		//    }
		//    return false;
		//}
		public static bool ModifyNumber(string value, int id)
		{
			string strSql = string.Format("update T_Student set number='{0}'  where id = @id", value);
			int n = SqlHelper.ExecuteNonQuery(strSql, new SqlParameter("@id", id));
			if (n != 0)
			{
				return true;
			}
			return false;
		}
		public static bool ModifyName(string value, int id)
		{
			string strSql = string.Format("update T_Student set name='{0}'  where id = @id", value);
			int n = SqlHelper.ExecuteNonQuery(strSql, new SqlParameter("@id", id));
			if (n != 0)
			{
				return true;
			}
			return false;
		}
		public static bool ModifyClass(string value, int id)
		{
			string strSql = string.Format("update T_Student set class='{0}'  where id = @id", value);
			int n = SqlHelper.ExecuteNonQuery(strSql, new SqlParameter("@id", id));
			if (n != 0)
			{
				return true;
			}
			return false;
		}

		public static bool ModifyPwd(string value, int id)
		{
			string strSql = string.Format("update T_Student set password='{0}'  where id = @id", value);
			int n = SqlHelper.ExecuteNonQuery(strSql, new SqlParameter("@id", id));
			if (n != 0)
			{
				return true;
			}
			return false;
		}

		public static bool SetPattern(int studentId, PatternType type)
		{
			string strSql = string.Format("update T_Student set pattern='{0}'  where id = @id", type);
			int n = SqlHelper.ExecuteNonQuery(strSql, new SqlParameter("@id", studentId));
			if (n != 0)
			{
				return true;
			}
			return false;
		}

		public static List<TheoryError> GetTheoryErrorList(int studentId)
		{
			//先得到
			string strSql = string.Format("select theory_error from T_Student where id = @id");
			object obj = SqlHelper.ExecuteScalar(strSql, new SqlParameter("@id", studentId));
			if (obj == null)
			{
				return null;
			}
			else
			{
				return LitJson.JsonMapper.ToObject<List<TheoryError>>(obj.ToString());
			}
		}

		public static List<OperateError> GetOperateErrorList(int studentId)
		{
			//先得到
			string strSql = string.Format("select operate_error from T_Student where id = @id");
			object obj = SqlHelper.ExecuteScalar(strSql, new SqlParameter("@id", studentId));
			if (obj == null)
			{
				return null;
			}
			else
			{
				return LitJson.JsonMapper.ToObject<List<OperateError>>(obj.ToString());
			}
		}

		public static bool UpdateTheoryError(int studentId, string strTheoryError)
		{
			string strSql = string.Format("update T_Student set theory_error='{0}'  where id = @id", strTheoryError);
			int n = SqlHelper.ExecuteNonQuery(strSql, new SqlParameter("@id", studentId));
			if (n != 0)
			{
				return true;
			}
			return false;
		}
		public static bool UpdateOperateError(int studentId, string strOperateError)
		{
			string strSql = string.Format("update T_Student set operate_error='{0}'  where id = @id", strOperateError);
			int n = SqlHelper.ExecuteNonQuery(strSql, new SqlParameter("@id", studentId));
			if (n != 0)
			{
				return true;
			}
			return false;
		}
	}
}
